package com.m.captcha.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/admin")
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";
    private static final Long SESSION_TIMEOUT = 60 * 1000L;

    @RequestMapping("/check")
    public Boolean check(String captcha, HttpSession session) {
        System.out.println(captcha);
        if(!StringUtils.hasLength(captcha)) {
            return false;
        }

        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
        if(captcha.equals(saveCaptcha)) {
            if(saveDate == null || System.currentTimeMillis() - saveDate.getTime() < SESSION_TIMEOUT) {
                return true;
            }
        }
        return false;
    }
}